﻿using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace Syspetro.Deploy.Jwt
{
    public class JWTEncryption
    {
        /// <summary>
        /// 获取Token中的身份信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="tokenValidation"></param>
        /// <returns></returns>
        public static ClaimsPrincipal GetPrincipalFromAccessTokenHs(string token, JwtTokenOptions jwtSettings)
        {
            try
            {
                var handler = new JwtSecurityTokenHandler();
                var tokenValidation = new TokenValidationParameters
                {
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.IssuerSigningKey)),
                    ValidateIssuerSigningKey = false,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                };
                return handler.ValidateToken(token, tokenValidation, out SecurityToken validatedToken);
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 获取Token中的身份信息
        /// </summary>
        /// <param name="token"></param>
        /// <param name="jwtSettings"></param>
        /// <param name="publicKeyPath"></param>
        /// <returns></returns>
        public static ClaimsPrincipal GetPrincipalFromAccessTokenRs(string token, string publicKeyPath)
        {
            try
            {
                string key = File.ReadAllText(publicKeyPath);
                var keyParams = JsonConvert.DeserializeObject<RSAParameters>(key);
                var handler = new JwtSecurityTokenHandler();
                var tokenValidation = new TokenValidationParameters
                {
                    IssuerSigningKey = new RsaSecurityKey(keyParams),
                    ValidateIssuerSigningKey = false,
                    ValidateIssuer = false,
                    ValidateAudience = false,
                    ValidateLifetime = false,
                };
                return handler.ValidateToken(token, tokenValidation, out SecurityToken validatedToken);
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 生成Token验证参数
        /// </summary>
        /// <param name="jwtSettings"></param>
        /// <returns></returns>
        public static TokenValidationParameters CreateTokenValidationParametersHs(JwtTokenOptions jwtSettings)
        {
            return new TokenValidationParameters
            {
                // 过期时间容错值
                ClockSkew = TimeSpan.FromSeconds(2),
                // 验证签发方密钥
                ValidateIssuerSigningKey = true,
                // 签发方密钥
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.IssuerSigningKey)),
                // 验证签发方
                ValidateIssuer = jwtSettings.ValidateIssuer,
                // 设置签发方
                ValidIssuer = jwtSettings.ValidIssuer,
                // 验证签收方
                ValidateAudience = jwtSettings.ValidateAudience,
                // 设置接收方
                ValidAudience = jwtSettings.ValidAudience,
                // 验证生存期
                ValidateLifetime = jwtSettings.ValidateLifetime,
            };
        }
        /// <summary>
        /// 生成Token验证参数
        /// </summary>
        /// <param name="jwtSettings"></param>
        /// <param name="publicKeyPath"></param>
        /// <returns></returns>
        public static TokenValidationParameters CreateTokenValidationParametersRs(JwtTokenOptions jwtSettings, string publicKeyPath)
        {
            #region 读取公钥
            if (!File.Exists(publicKeyPath))
            {
                string keyDir = Directory.GetCurrentDirectory();
                RSATokenHelper.GenerateAndSaveKey(keyDir, false);
            }
            string key = File.ReadAllText(publicKeyPath);
            var keyParams = JsonConvert.DeserializeObject<RSAParameters>(key);
            #endregion
            return new TokenValidationParameters
            {
                // 过期时间容错值
                ClockSkew = TimeSpan.FromSeconds(2),
                // 验证签发方密钥
                ValidateIssuerSigningKey = true,
                // 签发方密钥
                IssuerSigningKey = new RsaSecurityKey(keyParams),
                // 验证签发方
                ValidateIssuer = jwtSettings.ValidateIssuer,
                // 设置签发方
                ValidIssuer = jwtSettings.ValidIssuer,
                // 验证签收方
                ValidateAudience = jwtSettings.ValidateAudience,
                // 设置接收方
                ValidAudience = jwtSettings.ValidAudience,
                // 验证生存期
                ValidateLifetime = jwtSettings.ValidateLifetime,
            };
        }
    }
}
